package com.mk.config;

import com.mk.event.MqttMessageEvent;
import com.mk.utils.MqttUtil;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @author XueJinCha
 */
@Configuration
public class MqttConfig {

    @Value("${mqtt.broker.url}")
    private String brokerUrl;
    @Value("${mqtt.broker.username}")
    private String username;
    @Value("${mqtt.broker.password}")
    private String password;
    @Value("${mqtt.broker.clientId}")
    private String clientId;
    @Value("${mqtt.topics.default}")
    private String defaultTopic;
    @Value("${mqtt.topics.subscriptions}")
    private String[] topics;

    // 配置MQTT客户端工厂
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{brokerUrl});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

    // （接收消息:步骤一）定义一个消息通道，用于接收消息
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    // （接收消息:步骤二）配置消息驱动通道适配器，用于接收指定主题的消息
    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId, mqttClientFactory(), topics);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    // （接收消息:步骤三）配置消息处理器，用于处理接收到的消息
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler(ApplicationEventPublisher eventPublisher) {
        return message -> {
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            String payload = message.getPayload().toString();
            System.out.println("接收到消息: 主题 = " + topic + ", 内容 = " + payload);
            // 发布接收到的消息事件
            eventPublisher.publishEvent(new MqttMessageEvent(this, topic, payload));
        };
    }

    // 配置MQTT消息发送处理器
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic); // 设置默认主题
        return messageHandler;
    }

    // 定义一个消息通道，用于发送消息
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }
}
